package org.glut.wechat.personalcenter.service;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.glut.wechat.personalcenter.config.SmsConfig;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Service
public class SmsService {
    private final CloseableHttpClient httpClient;
    private final String apiUrl;
    private final String appcode;
    private final String templateId;
    private final String signId;

    public SmsService(CloseableHttpClient httpClient, SmsConfig smsConfig) {
        this.httpClient = httpClient;
        this.apiUrl = smsConfig.getApiUrl();
        this.appcode = smsConfig.getAppcode();
        this.templateId = smsConfig.getTemplateId();
        this.signId = smsConfig.getSignId();
    }

    /**
     * @description: 发送短信验证码
     * @param mobile
     * @param code
     * @param minute
     * @return java.lang.String
     * @date: 2025/8/5 15:18
     */
    public String sendVerificationCode(String mobile, String code, int minute) throws IOException {
        HttpPost httpPost = new HttpPost(apiUrl);

        // 设置认证头
        httpPost.addHeader("Authorization", "APPCODE " + appcode);

        // 请求Query参数
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("mobile", mobile));
        params.add(new BasicNameValuePair("templateId", templateId));
        params.add(new BasicNameValuePair("smsSignId", signId));

        // 构建模板，参数格式必须为 **code**:xxx,**minute**:xxx
        String paramValue = String.format("**code**:%s,**minute**:%d", code, minute);
        params.add(new BasicNameValuePair("param", paramValue));

        // 设置请求体
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        // 执行请求
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            return EntityUtils.toString(response.getEntity());
        }
    }
}